var express = require('express');
var router = express.Router();
var User = require('../modules/user');
var Post = require('../modules/post');

module.exports = router;

//API
router.get('/users', function (req, res) {
    User.getAll(function (err, users) {
        if (err || !users) return res.json({error: {code: 500, message: 'Internet Server error.'}});
        users = users.map(user => new User(user));
        res.json(users);
    });
});

router.get('/user/:name', function (req, res) {
    User.get(req.params.name, function (err, user) {
        if (err) return res.json({error: {code: 500, message: 'Internet Server error.'}});
        if (!user) return res.json({error: {code: 404, message: '用户不存在'}});
        res.json(new User(user));
    });
});

router.get('/posts/:name/:page', function (req, res, next) {
    var name = req.params.name;
    var p = req.query.page ? parseInt(req.query.page) : 1;
    var limit = 5;

    Post.getAll(name, p, limit, function (err, posts, total) {
        if (err)return res.json({'error': {code: 500, message: 'Internet Server error.'}});
        res.json({posts: posts});
    });
});

router.get('/post/:name/:postId', function (req, res, next) {
    Post.getOne(req.params.name,req.params.postId,function(err,post){
        if (err)return res.json({'error': {code: 500, message: 'Internet Server error.'}});
        res.json(post);
    });
});

router.put('/post/:id', function (req, res, next) {
    Post.update(req.params.id,req.body.post,function(err,ret){
        if (err)return res.json({'error': {code: 500, message: 'Internet Server error.'}});
        res.send({message:'success'});
    });
});